<template>
  <div v-loading="zhapaiLoading">
    <!-- ping -->
    <ping :ping="ping" @guanbi="pingguanbi($event)"></ping>
    <div class="tree-box moreLine" :style="{ paddingBottom: transferHeight.pb + 'px' }">
      <div>
        <span>设备所在辖区</span>
        <treesBox :treesBox="treesBox" @handleNodeClick="treeClick($event)"></treesBox>
      </div>
    </div>
    <div class="main_r" :style="{ minHeight: transferHeight.contentH + 'px' }">
      <!-- Echarts 图标 -->
      <div class="t">
        <el-row class="t_container">
          <el-col :span="12">
            <echarts-load v-if="pieFlag || reload_pie" :chartFlag="pieFlag" :reload="reload_pie" @refreshF="refreshPie" />
            <zpjc-pie v-else :zpjcPis="zpjcPis" />
          </el-col>
          <el-col :span="12">
            <echarts-load v-if="barFlag || reload_bar" :chartFlag="barFlag" :reload="reload_bar" @refreshF="refreshBar" />
            <zpjc-bar v-else :zpjcbars="zpjcbars" />
          </el-col>
        </el-row>
      </div>
      <div class="b">
        <!-- 搜索条件 -->
        <el-form :inline="true" :model="searchCriteria" class="demo-form-inline">
          <el-form-item label="设备状态:">
            <el-select v-model="searchCriteria.typeVal" class="inputWidth" clearable placeholder="请选择">
              <el-option label="抓拍正常" value="0"></el-option>
              <el-option label="抓拍异常" value="1"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="报障时间:">
            <el-date-picker
              v-model="searchCriteria.dataTime"
              :picker-options="pickerBeginDateBefore"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>-->
          <el-form-item>
            <el-input v-model.trim="searchCriteria.namer" width="200" prefix-icon="el-icon-search" clearable placeholder="输入设备名称或设备IP"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit2()" class="btnSizeStyle">查询</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table
          :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
          :cell-class-name="addClass"
          ref="multipleTable"
          border
          :data="tableData"
          style="width: 100%"
          highlight-current-row
          stripe
          :default-sort="{ prop: 'zpsj', order: 'descending' }"
          @sort-change="sortthiscolumn"
          v-loading="tableLoad"
        >
          <!-- 提示语句 -->
          <template slot="empty">{{ tableMessage }}</template>
          <el-table-column type="index" label="序号" min-width="50" align="center" />
          <el-table-column prop="sbmc" label="设备名称" sortable :show-overflow-tooltip="true" min-width="150">
            <template slot-scope="scope">
              <span>
                <svg class="iconfont" aria-hidden="true" style="width: 12px; height: 12px; vertical-align: middle; margin-right: 5px">
                  <use :xlink:href="'#el-icon-my' + (scope.row.zpzt === 1 ? 'warning' : 'generated')" style="font-size: 50px" />
                </svg>
                {{ scope.row.sbmc }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="zclxmc" label="设备类型" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-html="getsblx(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" min-width="200" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.zcsfmc + scope.row.zccsmc + scope.row.zcqxmc + scope.row.zcjdmc + scope.row.xxdz }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sbip" label="设备IP" min-width="120"></el-table-column>
          <el-table-column prop="ppmc" label="品牌" min-width="80"></el-table-column>
          <el-table-column prop="sbxh" label="型号" min-width="120" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="zptp" label="抓拍结果" min-width="80">
            <template slot-scope="scope">
              <el-image class="table_cell_image" :src="scope.row.zptp + '_25Percent.jpg'" @click.stop="handleClickItem" :preview-src-list="[scope.row.zptp]">
                <div slot="error">
                  <img style="width: 100%" src="@/assets/images/zanWuTuPian.jpg" alt />
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="zpsj" label="检测时间" sortable="custom" min-width="150">
            <template slot-scope="scope">{{ scope.row.zpsj | dateFormat }}</template>
          </el-table-column>
          <el-table-column prop="zclxmc" label="宿主" min-width="98">
            <template slot-scope="scope">
              <!-- <el-tooltip
                class="item"
                :content="item.SZMC"
                placement="top-start"
                popper-class="atooltip"
                v-for="item in scope.row.szs"
                :key="item.SZLX"
                v-show="scope.row.szs.length === 0 ? false : true"
              >
                <svg class="iconfont" aria-hidden="true" style="width: 20px; height: 20px; vertical-align: middle; margin-right: 5px">
                  <use :xlink:href="'#el-icon-my' + shuZhu[item.SZLX]" style="font-size: 50px" />
                </svg>
              </el-tooltip>-->
              <span v-for="(item, index) in scope.row.szs" :key="index">
                <el-tooltip v-if="Number(item.SZLX) >= 0" class="item" placement="top-start" popper-class="atooltip">
                  <div slot="content">{{ item.SZMC }}</div>
                  <svg class="iconfont" aria-hidden="true" style="width: 20px; height: 20px">
                    <!-- 0运维主机 1卡口 2电警 -->
                    <use :xlink:href="`#el-icon-mysuzhu_${item.SZLX}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
                <svg v-else class="iconfont" aria-hidden="true" style="width: 20px; height: 20px">
                  <!-- 0运维主机 1卡口 2电警 -->
                  <use :xlink:href="`#el-icon-my${grayIcon[index]}`" style="font-size: 50px" />
                </svg>
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="gdzt" label="工单状态" min-width="120">
            <template slot-scope="scope">
              <span :class="[`type${scope.row.gdzt}`, 'type']">{{ type[scope.row.gdzt] }}</span>
            </template>
          </el-table-column>-->
          <el-table-column fixed="right" label="操作" min-width="150" align="right">
            <template slot-scope="scope">
              <div class="operations">
                <!-- 不可以点击加上 noAction这个类名 -->
                <!-- <el-button type="text" @click="handleClick(scope.row)">编辑</el-button> -->
                <el-button type="text" @click="paiZao(scope.row)" v-preventReClick :disabled="!scope.row.sbip || quanxianBtns.btn1 ? false : true">抓拍</el-button>
                <span class="operation"></span>
                <!-- <el-button
                  type="text"
                  :disabled="scope.row.sbip !== '' && scope.row.sbip !== null ? false : true"
                  @click="yuanChenKZ(scope.row)"
                >远程控制</el-button>-->
                <el-link
                  :disabled="scope.row.sbip !== '' && scope.row.sbip !== null ? false : true"
                  :type="scope.row.sbip !== '' && scope.row.sbip !== null ? 'primary' : 'info'"
                  :underline="false"
                  :href="'http://' + scope.row.sbip"
                  target="_blank"
                  >远程控制</el-link
                >
                <span class="operation"></span>
                <el-button type="text" @click="showPingOk(scope.row)" :disabled="scope.row.sbip !== '' && scope.row.sbip !== null ? false : true">ping</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row class="page-row">
          <el-col :span="12">
            <div class="bigBOx btnBefore">
              <div class="imgBox">
                <svg class="iconfont imgIcon" aria-hidden="true">
                  <use xlink:href="#el-icon-mygenerated" />
                </svg>
                <span>抓拍正常</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon" aria-hidden="true">
                  <use xlink:href="#el-icon-mywarning" />
                </svg>
                <span>抓拍异常</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_0" />
                </svg>
                <span>运维主机</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_1" />
                </svg>
                <span>卡口</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_2" />
                </svg>
                <span>电子警察</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12" style="height: 47px; display: table">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total"
            ></el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import zpjcPie from '@/components/Echarts/zpjcPie'
import zpjcBar from '@/components/Echarts/zpjcBar'
import Ping from '@/components/ping/index.vue'
import treesBox from '@/components/treesBox/index.vue'
import { getUrl } from '@/utils/getUrl.js'
import { xunJian, ziC } from '@/utils/allUrl.js'
// import { endLoading } from '@/utils/loading.js'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
import echartsLoad from '@/components/Echarts/echartsLoad'
import { threeLevelH } from '@/assets/js/calcHeight'
import { getImages } from '@/assets/js/getImage.js'
export default {
  computed: {
    transferHeight: function () {
      // 计算屏幕滚动高度 - nav - 导航栏
      return {
        contentH: window.innerHeight - threeLevelH,
        pb: threeLevelH,
      }
    },
  },
  components: { zpjcPie, zpjcBar, Ping, treesBox, echartsLoad },
  data() {
    return {
      ping: {
        name: '', // ping设备名称
        speedOpen: false, // ping框
        ip: '',
      },
      zpjcPis: [],
      zpjcbars: [],
      //  0 '未生成'
      //  1 '已受理 (',当前处理人可看)
      //  2 '待确认',
      //  3 '正常关闭',
      //  4 '驳回',
      //  5 '挂起',
      //  6 '外派',
      //  7 '异常关闭',
      type: ['未生成', '已受理', '待确认', '正常关闭', '驳回', '挂起', '外派'], // 正常和异常关闭不需要
      shuZhu: ['suzhu_0', 'suzhu_1', 'suzhu_2'],
      treesBox: {
        url: 'ZI_CHAN',
        // url: 'yonghu/selectYongHuXiaQuByZc',
        GZKZ: [45],
      }, // tree图的请求地址
      zicanOptions: [], // 资产类型
      searchCriteria: {
        typeVal: '', // 设备类型
        dataTime: '', // 报障时间
        namer: '',
      },
      tableData: [],
      currentPage: 1, // 页码
      pageSize: 10, // 页数
      total: 0, // 总条数
      flag: false, // echarts渲染
      pickerBeginDateBefore: {
        // 设置只能选择到今天及以前的日期
        disabledDate(time) {
          return time.getTime() >= Date.now()
        },
      },
      xianQu: null, // 辖区搜索条件
      pieFlag: false, // 环形图
      barFlag: false,
      zhapaiLoading: false,
      tableMessage: '',
      tableTimer: null,
      pieTimer: null,
      barTimer: null,
      reload_pie: false,
      reload_bar: false,
      grayIcon: ['zhuji_hui', 'kakou_hui', 'dzjc_hui'],
      listQuery: {
        sortby: 'DESC',
        order: 'zpsj',
      },
      quanxianBtns: {
        btn1: false,
      },
    }
  },
  watch: {
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.tableData = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
    pieFlag(newVal, oldVal) {
      this.pieTimer = setTimeout(() => {
        if (this.pieFlag) {
          this.pieFlag = false
          this.reload_pie = true
        }
      }, timeLoad)
    },
    barFlag(newVal, oldVal) {
      this.barTimer = setTimeout(() => {
        if (this.barFlag) {
          this.barFlag = false
          this.reload_bar = true
        }
      }, timeLoad)
    },
  },
  created() {
    // 权限按钮
    this.jurisdictionBtn()
    // this.treeData = JSON.parse(getUrl('xiaquCity'))
    // 获取饼状图
    this.getPie()
    this.getBar()
    // 获取数据
    this.listQuery.sortby = 'DESC'
    this.listQuery.order = 'zpsj' // 降序
    this.getShuju()
    // 获取资产
    this.getzican()
  },
  methods: {
    // 获取按钮权限
    jurisdictionBtn() {
      const menus = JSON.parse(getUrl('jurisdiction'))
      menus.forEach((item) => {
        if (item.qxdm === 'XJZX_YXJC_ZPSBJC') {
          item.children.forEach((item2) => {
            if (item2.qxdm === 'zhuapai') {
              this.quanxianBtns.btn1 = true // 抓拍
            }
          })
        }
      })
    },
    getsblx(row) {
      return `<span>${row.zclxmc1 ? row.zclxmc1 + ' / ' : ''}</span>
                <span>${row.zclxmc2 ? row.zclxmc2 + ' / ' : ''}</span>
                <span>${row.zclxmc3}</span>`
    },
    getShuju() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const user = JSON.parse(getUrl('userconter'))
      const params = new URLSearchParams()
      params.append('userId', user.id)
      params.append('order', this.listQuery.order)
      params.append('sort', this.listQuery.sortby)
      params.append('M_', this.currentPage)
      params.append('N_', this.pageSize)
      this.setList(params)
    },
    async setList(params) {
      const { data: res } = await this.$http.post(`${xunJian}zpsb/selectZhuaPaiSheBei`, params)
      this.tableLoad = false // 表格加载中样式
      switch (res.code) {
        case '0000': // 操作成功
          this.tableData = getImages(res.data.list, 'zptp')
          this.total = res.data.countList
          break
        default:
          this.tableData = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
    },
    // 获取资产
    async getzican() {
      const params = new URLSearchParams()
      params.append('FLXID', 0)
      const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      const city = JSON.stringify(res.data.list)
      const newCity = city.replace(/id/g, 'value')
      const cityList = newCity.replace(/lxmc/g, 'label')
      this.zicanOptions = JSON.parse(cityList)
    },
    // 获取饼状图数据
    async getPie() {
      clearTimeout(this.pieFlag)
      this.pieFlag = true
      const user = JSON.parse(getUrl('userconter'))
      const params = new URLSearchParams()
      params.append('userId', user.id)
      // params.append('ZCLX', 5)
      const { data: res } = await this.$http.post(`${xunJian}zpsb/selectTBSJ`, params)
      this.pieFlag = false
      switch (res.code) {
        case '0000':
          this.zpjcPis = [
            // { id: 0, value: res.data.tbs.ZC_, name: '抓拍正常', color: '#5AB1EF' },
            // { id: 1, value: res.data.tbs.YC_, name: '抓拍异常', color: '#F96E86' },
            { id: 1, value: res.data.tbs.YC_, name: '抓拍异常' },
            { id: 0, value: res.data.tbs.ZC_, name: '抓拍正常' },
          ]
          // var arr = this.zpjcPis.sort(this.compare('id'))
          // console.log(arr)
          break
        case '0013': // 暂无数据
          this.zpjcPis = [
            // { id: 0, value: 0, name: '抓拍正常', color: '#5AB1EF' },
            // { id: 1, value: 0, name: '抓拍异常', color: '#F96E86' },
            { value: 0, name: '抓拍异常' },
            { value: 0, name: '抓拍正常' },
          ]
          break
        default:
          this.reload_pie = true
          break
      }
    },
    compare(property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    async getBar() {
      clearTimeout(this.barFlag)
      this.barFlag = true
      const user = JSON.parse(getUrl('userconter'))
      const params = new URLSearchParams()
      params.append('userId', user.id)
      params.append('type', 'MC')
      params.append('zclx', '45')
      const { data: res } = await this.$http.post(`${xunJian}zpsb/selectBMTop`, params)
      this.barFlag = false
      switch (res.code) {
        case '0000':
          var a = []
          var b = []
          res.data.tops.forEach((item) => {
            a.push(item.zcmc)
            b.push(item.count)
          })
          this.zpjcbars = {
            cityList: a,
            cityData: b,
          }
          break
        case '0013': // 暂无数据
          this.zpjcbars = {
            cityList: ['摄像机', '测试3', '枪型摄像机(勿动)', '办公室二号(勿动)', '海康'],
            cityData: [0, 0, 0, 0, 0],
          }
          break
        default:
          this.reload_pie = true
          break
      }
    },
    refreshPie() {
      this.reload_pie = false
      this.getPie()
    },
    refreshBar() {
      this.reload_bar = false
      this.getBar()
    },
    onSubmit2() {
      this.currentPage = 1
      this.pageSize = 10
      this.onSubmit(1, 10)
    },
    async onSubmit(size, current, val) {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const { typeVal, dataTime, namer } = this.searchCriteria
      const params = new URLSearchParams()
      const user = JSON.parse(getUrl('userconter'))
      if (val) {
        if (val.levels === 1) {
          params.append('SF', val.label)
        } else if (val.levels === 2) {
          params.append('CS', val.label)
        } else if (val.levels === 3) {
          params.append('QX', val.label)
        } else if (val.levels === 4) {
          params.append('XZJD', val.label)
        }
      } else {
        if (this.xianQu) {
          if (this.xianQu.levels === 1) {
            params.append('SF', this.xianQu.label)
          } else if (this.xianQu.levels === 2) {
            params.append('CS', this.xianQu.label)
          } else if (this.xianQu.levels === 3) {
            params.append('QX', this.xianQu.label)
          } else if (this.xianQu.levels === 4) {
            params.append('XZJD', this.xianQu.label)
          }
        }
      }
      if (dataTime) {
        params.append('ZPSJSTART', dataTime[0])
        params.append('ZPSJEND', dataTime[1])
      }
      params.append('userId', user.id)
      params.append('ZPZT', typeVal)
      params.append('order', this.listQuery.order)
      params.append('sort', this.listQuery.sortby)
      params.append('SBMC', namer)
      params.append('M_', size)
      params.append('N_', current)
      this.setList(params)
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.onSubmit(this.currentPage, val)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.onSubmit(val, this.pageSize)
    },
    // 点击蒙版关闭图片
    handleClickItem() {
      this.$nextTick(() => {
        const domImageMask = document.querySelector('.el-image-viewer__mask') // 获取遮罩层dom
        if (!domImageMask) {
          return
        }
        domImageMask.addEventListener('click', () => {
          // 点击遮罩层时调用关闭按钮的 click 事件
          document.querySelector('.el-image-viewer__close').click()
        })
      })
    },

    // 拍照/抓拍
    async paiZao(scope) {
      this.zhapaiLoading = true
      const a = setTimeout(() => {
        this.zhapaiLoading = false
      }, 10000)
      const params = new URLSearchParams()
      params.append('ip', scope.sbip)
      // const { data: res } = await this.$http.post(`${sheB}capturePicture/manual`, params)
      const { data: res } = await this.$http.post(`${ziC}zcgl/deviceManual`, params) // 更新于2021-04-13
      if (res.code === '0014') {
        clearTimeout(a)
        this.zhapaiLoading = false
        return ''
      } else if (res.code !== '0000') {
        clearTimeout(a)
        this.zhapaiLoading = false
        return this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
      setTimeout(() => {
        this.$message({
          type: 'success',
          message: res.message,
          center: true,
        })
        this.getShuju()
        this.getPie()
        this.getBar()
        clearTimeout(a)
        this.zhapaiLoading = false
      }, 1000)
    },
    sortthiscolumn(column) {
      // 排序
      this.listQuery.order = 'zpsj'
      if (column.order === 'descending') {
        this.listQuery.sortby = 'DESC'
      } else if (column.order === 'ascending') {
        this.listQuery.sortby = 'ASC'
      } else {
        this.listQuery.sortby = ''
        this.listQuery.order = '' // 没有排序
      }
      this.currentPage = 1
      // this.pageSize = 10
      this.getShuju()
    },
    // ping
    showPingOk(scope) {
      this.ping.speedOpen = true
      this.ping.ip = scope.sbip
      this.ping.name = scope.sbmc
    },
    // ping组件
    pingguanbi(val) {
      this.ping = {
        speedOpen: val.type,
        name: '', // ping设备名称
        ip: '',
      }
    },
    // tree形搜索
    treeClick(e) {
      this.pageSize = 10
      this.currentPage = 1
      this.onSubmit(1, 10, e.type)
      this.xianQu = e.type
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      // console.log('row:', row, 'column:', column, 'rowIndex:', rowIndex, 'columnIndex:', columnIndex)
      // if (columnIndex === 0) {
      //   return 'fontColor'
      // }
    },
  },
}
</script>
<style lang="scss" scoped>
// ::v-deep .el-icon-circle-close {
//   font-size: 45px;
// }
@import '@/assets/scss/xjzxCommon.scss';
.t_container {
  width: 100%;
  height: 100%;
  .el-col {
    height: 100%;
  }
}
</style>
